
import React, { useState, useEffect, useMemo } from 'react';
import { useParams, useSearchParams, Link } from 'react-router-dom';
import { 
    ArrowLeft, Download, RotateCcw, FileText, X, 
    Check, AlertTriangle, Info, AlertOctagon, 
    ChevronRight, Copy, History, Search, Filter 
} from 'lucide-react';
import { getRecordById, getIssuesByRecord, getTaskById } from '../services/mockService';
import { ScanRecord, ScanIssue, TaskType, ConfirmationStatus, ConfirmationType, ScanTask, IssueSeverity, ConfirmationHistoryItem } from '../types';
import { ScanStatusBadge } from '../components/StatusBadge';

// --- Sub-components for Detail Drawer ---

const DetailRow: React.FC<{ label: string; value: React.ReactNode; highlight?: boolean }> = ({ label, value, highlight }) => (
    <div className="flex items-start justify-between py-2 border-b border-slate-50 last:border-0">
        <span className="text-xs font-medium text-slate-500">{label}</span>
        <span className={`text-sm font-medium text-right ${highlight ? 'text-indigo-600' : 'text-slate-800'}`}>{value || '-'}</span>
    </div>
);

const TimelineItem: React.FC<{ item: any; isLast: boolean }> = ({ item, isLast }) => (
    <div className="relative pl-6 pb-6">
        {!isLast && <div className="absolute left-[5px] top-2 bottom-0 w-px bg-slate-200"></div>}
        <div className="absolute left-0 top-1.5 w-2.5 h-2.5 rounded-full bg-indigo-400 ring-4 ring-white"></div>
        <div className="flex flex-col gap-1">
            <div className="flex items-center justify-between">
                <span className="text-xs text-slate-500">{new Date(item.timestamp).toLocaleString()} · {item.actor}</span>
                {item.action === 'create' ? (
                    <span className="text-[10px] text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded border border-emerald-100">Created</span>
                ) : (
                    <span className="text-[10px] text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded border border-blue-100">Updated</span>
                )}
            </div>
            <div className="text-sm font-medium text-slate-800">
                Type: <span className="font-bold">{item.type}</span>
            </div>
            {item.note && <div className="text-xs text-slate-600 bg-slate-50 p-2 rounded border border-slate-100 mt-1">{item.note}</div>}
        </div>
    </div>
);

// --- Main Component ---

export const ScanDetailPage: React.FC = () => {
  const { recordId } = useParams<{ recordId: string }>();
  const [searchParams] = useSearchParams();
  const typeParam = searchParams.get('type') as TaskType;
  
  const [record, setRecord] = useState<ScanRecord | null>(null);
  const [task, setTask] = useState<ScanTask | null>(null);
  const [issues, setIssues] = useState<ScanIssue[]>([]);
  
  // Filter States
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<'ALL' | ConfirmationStatus>('ALL');
  const [severityFilter, setSeverityFilter] = useState<IssueSeverity[]>([]);

  // Selection & Drawer State
  const [selectedIssue, setSelectedIssue] = useState<ScanIssue | null>(null);
  const [confirmType, setConfirmType] = useState<ConfirmationType | ''>('');
  const [confirmNote, setConfirmNote] = useState('');

  useEffect(() => {
    if (recordId) {
      const r = getRecordById(recordId);
      setRecord(r);
      if (r) {
         const t = getTaskById(r.taskId);
         setTask(t || null);
         setIssues(getIssuesByRecord(r.id, typeParam));
      }
    }
  }, [recordId, typeParam]);

  // Computed Metrics
  const metrics = useMemo(() => {
      const counts = {
          total: issues.length,
          confirmed: issues.filter(i => i.confirmationStatus === ConfirmationStatus.CONFIRMED).length,
          unconfirmed: issues.filter(i => i.confirmationStatus === ConfirmationStatus.UNCONFIRMED).length,
          critical: issues.filter(i => i.severity === IssueSeverity.CRITICAL).length,
          warning: issues.filter(i => i.severity === IssueSeverity.WARNING).length,
          info: issues.filter(i => i.severity === IssueSeverity.INFO).length,
      };
      return counts;
  }, [issues]);

  // Filter Logic
  const filteredIssues = useMemo(() => {
      return issues.filter(issue => {
          const matchesSearch = 
            issue.ruleName.toLowerCase().includes(searchTerm.toLowerCase()) ||
            issue.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
            issue.filePath.toLowerCase().includes(searchTerm.toLowerCase());
          
          const matchesStatus = statusFilter === 'ALL' || issue.confirmationStatus === statusFilter;
          
          const matchesSeverity = severityFilter.length === 0 || severityFilter.includes(issue.severity);

          return matchesSearch && matchesStatus && matchesSeverity;
      });
  }, [issues, searchTerm, statusFilter, severityFilter]);

  const handleSeverityToggle = (sev: IssueSeverity) => {
      setSeverityFilter(prev => 
          prev.includes(sev) ? prev.filter(s => s !== sev) : [...prev, sev]
      );
  };

  const handleConfirmSubmit = () => {
      if (!selectedIssue || !confirmType) return;

      setIssues(prev => prev.map(iss => {
          if (iss.id === selectedIssue.id) {
              const action: 'create' | 'update' | 'revoke' = iss.confirmationStatus === ConfirmationStatus.CONFIRMED ? 'update' : 'create';
              const newHistoryItem: ConfirmationHistoryItem = {
                  id: `h-${Date.now()}`,
                  timestamp: new Date().toISOString(),
                  actor: 'CurrentUser',
                  type: confirmType as ConfirmationType,
                  note: confirmNote,
                  action: action
              };
              return {
                  ...iss,
                  confirmationStatus: ConfirmationStatus.CONFIRMED,
                  confirmationType: confirmType as ConfirmationType,
                  confirmationNote: confirmNote,
                  history: [newHistoryItem, ...iss.history] // Prepend new history
              };
          }
          return iss;
      }));

      // Update the currently selected issue reference to reflect changes immediately in UI
      setSelectedIssue(prev => {
          if (!prev) return null;
          const action: 'create' | 'update' | 'revoke' = prev.confirmationStatus === ConfirmationStatus.CONFIRMED ? 'update' : 'create';
          const newHistoryItem: ConfirmationHistoryItem = {
              id: `h-${Date.now()}`,
              timestamp: new Date().toISOString(),
              actor: 'CurrentUser',
              type: confirmType as ConfirmationType,
              note: confirmNote,
              action: action
          };
          return {
              ...prev,
              confirmationStatus: ConfirmationStatus.CONFIRMED,
              confirmationType: confirmType as ConfirmationType,
              history: [newHistoryItem, ...prev.history]
          };
      });

      setConfirmNote('');
      setConfirmType('');
  };

  if (!record || !task) return <div className="p-8 text-center text-slate-400">Loading...</div>;

  return (
    <div className="flex h-[calc(100vh-80px)] -m-8 overflow-hidden">
      {/* LEFT PANEL: List & Header */}
      <div className="flex-1 flex flex-col min-w-0 bg-slate-50/50">
         {/* Header */}
         <div className="bg-white border-b border-slate-200 p-6">
            <div className="flex items-start justify-between mb-6">
                <div>
                    <div className="flex items-center gap-3 mb-2">
                        <Link to={`/task/${task.id}`} className="text-slate-400 hover:text-slate-600"><ArrowLeft className="w-4 h-4"/></Link>
                        <h1 className="text-xl font-bold text-slate-900">{task.name}</h1>
                        <ScanStatusBadge status={record.status} />
                    </div>
                    <div className="flex items-center gap-4 text-xs text-slate-500">
                        <span>ID: {record.id}</span>
                        <span>•</span>
                        <span>{record.branch}</span>
                        <span>•</span>
                        <span>{new Date(record.startTime).toLocaleString()}</span>
                        <span>•</span>
                        <span>Creator: {record.creator}</span>
                    </div>
                </div>
                <div className="flex gap-2">
                    <button className="px-3 py-2 text-xs font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 flex items-center gap-2">
                        <RotateCcw className="w-3.5 h-3.5"/> Re-scan
                    </button>
                    <button className="px-3 py-2 text-xs font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 flex items-center gap-2">
                        <Download className="w-3.5 h-3.5"/> Export
                    </button>
                    <button className="px-3 py-2 text-xs font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 flex items-center gap-2">
                        <FileText className="w-3.5 h-3.5"/> Log
                    </button>
                </div>
            </div>

            {/* Metrics Cards */}
            <div className="grid grid-cols-4 gap-4 mb-2">
                 <div className="bg-white p-3 rounded-xl border border-slate-100 shadow-sm">
                     <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Total Issues</span>
                     <div className="text-2xl font-bold text-slate-800 mt-1">{metrics.total}</div>
                 </div>
                 <div className="bg-white p-3 rounded-xl border border-slate-100 shadow-sm">
                     <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Severity</span>
                     <div className="flex items-baseline gap-3 mt-1">
                         <span className="text-lg font-bold text-rose-500">{metrics.critical}</span>
                         <span className="text-lg font-bold text-amber-500">{metrics.warning}</span>
                         <span className="text-lg font-bold text-blue-500">{metrics.info}</span>
                     </div>
                     <div className="flex gap-3 text-[9px] text-slate-400 uppercase font-medium mt-1">
                         <span className="text-rose-400">Crit</span>
                         <span className="text-amber-400">Warn</span>
                         <span className="text-blue-400">Info</span>
                     </div>
                 </div>
                 <div className="bg-white p-3 rounded-xl border border-slate-100 shadow-sm">
                     <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Confirmation</span>
                     <div className="flex items-baseline gap-3 mt-1">
                         <span className="text-lg font-bold text-emerald-600">{metrics.confirmed}</span>
                         <span className="text-lg font-bold text-slate-400">{metrics.unconfirmed}</span>
                     </div>
                     <div className="flex gap-3 text-[9px] text-slate-400 uppercase font-medium mt-1">
                         <span className="text-emerald-500">Done</span>
                         <span>Pending</span>
                     </div>
                 </div>
                 <div className="bg-white p-3 rounded-xl border border-slate-100 shadow-sm">
                     <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Duration</span>
                     <div className="text-2xl font-bold text-slate-800 mt-1">{record.duration}</div>
                     <div className="text-[10px] text-slate-400 truncate mt-1">{record.extensionData?.['apiVersion']}</div>
                 </div>
            </div>
         </div>

         {/* Filters */}
         <div className="px-6 py-3 bg-white border-b border-slate-200 flex items-center gap-4 overflow-x-auto">
             <div className="flex items-center gap-2 border-r border-slate-200 pr-4">
                 <span className="text-xs font-medium text-slate-500">Severity:</span>
                 {[IssueSeverity.CRITICAL, IssueSeverity.WARNING, IssueSeverity.INFO].map(sev => (
                     <label key={sev} className="flex items-center gap-1.5 cursor-pointer">
                         <input 
                            type="checkbox" 
                            checked={severityFilter.includes(sev)}
                            onChange={() => handleSeverityToggle(sev)}
                            className="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 w-3.5 h-3.5" 
                         />
                         <span className={`text-xs font-medium ${
                             sev === IssueSeverity.CRITICAL ? 'text-rose-600' : sev === IssueSeverity.WARNING ? 'text-amber-600' : 'text-blue-600'
                         }`}>{sev}</span>
                     </label>
                 ))}
             </div>
             
             <div className="flex items-center gap-2 border-r border-slate-200 pr-4">
                 <span className="text-xs font-medium text-slate-500">Status:</span>
                 <select 
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value as any)}
                    className="text-xs border-none bg-slate-50 rounded-md py-1 pl-2 pr-6 focus:ring-0 font-medium text-slate-700"
                 >
                     <option value="ALL">All Status</option>
                     <option value={ConfirmationStatus.UNCONFIRMED}>Unconfirmed</option>
                     <option value={ConfirmationStatus.CONFIRMED}>Confirmed</option>
                 </select>
             </div>

             <div className="flex-1 relative max-w-md">
                 <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" />
                 <input 
                    type="text" 
                    placeholder="Search description, rule, or path..." 
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-8 pr-4 py-1.5 bg-slate-50 border-none rounded-md text-xs focus:ring-1 focus:ring-indigo-500 placeholder:text-slate-400"
                 />
             </div>
             
             <button 
                onClick={() => { setSearchTerm(''); setStatusFilter('ALL'); setSeverityFilter([]); }}
                className="text-xs text-indigo-600 hover:underline whitespace-nowrap"
             >
                 Reset
             </button>
         </div>

         {/* Issue List */}
         <div className="flex-1 overflow-y-auto p-6">
             <div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
                 <table className="w-full text-left">
                     <thead className="bg-slate-50 border-b border-slate-100 text-xs text-slate-500 font-medium uppercase tracking-wider">
                         <tr>
                             <th className="px-4 py-3 w-10"><input type="checkbox" className="rounded border-slate-300" /></th>
                             <th className="px-4 py-3">Level</th>
                             <th className="px-4 py-3">Rule / Description</th>
                             <th className="px-4 py-3">File Path</th>
                             <th className="px-4 py-3 w-32">Status</th>
                             <th className="px-4 py-3 w-16 text-center">Inherit</th>
                         </tr>
                     </thead>
                     <tbody className="divide-y divide-slate-50">
                         {filteredIssues.map(issue => (
                             <tr 
                                key={issue.id} 
                                onClick={() => setSelectedIssue(issue)}
                                className={`cursor-pointer transition-colors group ${selectedIssue?.id === issue.id ? 'bg-indigo-50/60' : 'hover:bg-slate-50'}`}
                             >
                                 <td className="px-4 py-3"><input type="checkbox" className="rounded border-slate-300" onClick={e => e.stopPropagation()} /></td>
                                 <td className="px-4 py-3">
                                     {issue.severity === IssueSeverity.CRITICAL ? <AlertOctagon className="w-4 h-4 text-rose-500"/> :
                                      issue.severity === IssueSeverity.WARNING ? <AlertTriangle className="w-4 h-4 text-amber-500"/> :
                                      <Info className="w-4 h-4 text-blue-500"/>}
                                 </td>
                                 <td className="px-4 py-3">
                                     <div className="flex flex-col gap-0.5">
                                         <span className={`font-semibold text-sm ${selectedIssue?.id === issue.id ? 'text-indigo-900' : 'text-slate-800'}`}>{issue.ruleName}</span>
                                         <span className="text-xs text-slate-500 line-clamp-1">{issue.description}</span>
                                     </div>
                                 </td>
                                 <td className="px-4 py-3 text-xs text-slate-500 font-mono truncate max-w-[200px]">
                                     {issue.filePath}
                                 </td>
                                 <td className="px-4 py-3">
                                    {issue.confirmationStatus === ConfirmationStatus.CONFIRMED ? (
                                        <span className="inline-flex px-2 py-0.5 rounded text-[10px] font-semibold bg-indigo-100 text-indigo-700 border border-indigo-200">
                                            {issue.confirmationType}
                                        </span>
                                    ) : (
                                        <span className="inline-flex px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-100 text-slate-500">
                                            Pending
                                        </span>
                                    )}
                                 </td>
                                 <td className="px-4 py-3 text-center">
                                     {issue.inheritedFromRecordId ? (
                                         <div className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-amber-50 text-amber-600" title="Inherited">
                                             <History className="w-3.5 h-3.5" />
                                         </div>
                                     ) : <span className="text-slate-300">-</span>}
                                 </td>
                             </tr>
                         ))}
                     </tbody>
                 </table>
                 {filteredIssues.length === 0 && (
                     <div className="p-12 text-center text-slate-400">
                         <Filter className="w-8 h-8 mx-auto mb-3 opacity-50" />
                         <p>No issues match your filters.</p>
                     </div>
                 )}
             </div>
             <div className="mt-4 flex justify-between items-center text-xs text-slate-500">
                 <span>Showing {filteredIssues.length} of {issues.length} items</span>
                 <div className="flex gap-2">
                     <button disabled className="px-2 py-1 border rounded bg-slate-50 opacity-50">Prev</button>
                     <button className="px-2 py-1 border rounded hover:bg-white">Next</button>
                 </div>
             </div>
         </div>
      </div>

      {/* RIGHT PANEL: Side Drawer */}
      <div className={`w-[450px] bg-white border-l border-slate-200 shadow-xl flex flex-col transition-transform duration-300 ease-in-out ${selectedIssue ? 'translate-x-0' : 'translate-x-full'} absolute right-0 top-0 bottom-0 z-20`}>
          {selectedIssue ? (
              <>
                  {/* Drawer Header */}
                  <div className="p-6 border-b border-slate-100 flex items-start justify-between bg-slate-50/30">
                      <div className="flex flex-col gap-2">
                          <div className="flex items-center gap-2">
                                {selectedIssue.severity === IssueSeverity.CRITICAL ? 
                                    <span className="px-2 py-0.5 rounded bg-rose-100 text-rose-700 text-[10px] font-bold uppercase tracking-wide">Critical</span> :
                                selectedIssue.severity === IssueSeverity.WARNING ?
                                    <span className="px-2 py-0.5 rounded bg-amber-100 text-amber-700 text-[10px] font-bold uppercase tracking-wide">Warning</span> :
                                    <span className="px-2 py-0.5 rounded bg-blue-100 text-blue-700 text-[10px] font-bold uppercase tracking-wide">Info</span>
                                }
                                <span className="text-xs text-slate-400 font-mono">{selectedIssue.id}</span>
                          </div>
                          <h2 className="text-lg font-bold text-slate-900 leading-tight">{selectedIssue.ruleName}</h2>
                      </div>
                      <button 
                        onClick={() => setSelectedIssue(null)}
                        className="p-1.5 hover:bg-slate-100 rounded-full text-slate-400 transition-colors"
                      >
                          <X className="w-5 h-5" />
                      </button>
                  </div>

                  {/* Drawer Content */}
                  <div className="flex-1 overflow-y-auto">
                      <div className="p-6 space-y-6">
                          
                          {/* File Info */}
                          <div className="bg-slate-50 p-3 rounded-lg border border-slate-200 font-mono text-xs text-slate-600 break-all flex items-center gap-2">
                             <FileText className="w-4 h-4 text-slate-400 flex-shrink-0" />
                             {selectedIssue.filePath} : <span className="text-indigo-600 font-bold">{selectedIssue.lineNumber}</span>
                          </div>

                          {/* Issue Details Table */}
                          <div>
                              <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">Issue Details</h3>
                              <div className="space-y-0">
                                  <DetailRow label="Current Status" value={
                                      selectedIssue.confirmationStatus === ConfirmationStatus.CONFIRMED ? 
                                      <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 text-[10px] font-bold"><Check className="w-3 h-3"/> {selectedIssue.confirmationType}</span> : 
                                      <span className="text-slate-400 italic">Unconfirmed</span>
                                  } />
                                  {/* Dynamic Fields */}
                                  {task.issueFields.filter(f => f.type !== 'code').map(field => (
                                      <DetailRow 
                                        key={field.key} 
                                        label={field.label} 
                                        value={selectedIssue.extensionData?.[field.key]} 
                                      />
                                  ))}
                              </div>
                          </div>

                          {/* Description */}
                          <div>
                              <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">Description</h3>
                              <p className="text-sm text-slate-700 leading-relaxed bg-white p-3 border border-slate-100 rounded-lg">
                                  {selectedIssue.description}
                                  {selectedIssue.extensionData?.suggestion && (
                                      <div className="mt-3 pt-3 border-t border-slate-100">
                                          <span className="text-xs font-bold text-slate-500 block mb-1">Suggestion:</span>
                                          <code className="text-xs bg-slate-100 px-1 py-0.5 rounded text-slate-800">{selectedIssue.extensionData.suggestion}</code>
                                      </div>
                                  )}
                              </p>
                          </div>

                          {/* Code Snippet(s) */}
                          {(() => {
                              // 收集所有代码片段
                              const codeSnippets: Array<{label: string; code: string; language?: string}> = [];
                              
                              // 主要代码片段
                              if (selectedIssue.codeSnippet) {
                                  codeSnippets.push({
                                      label: '主要代码',
                                      code: selectedIssue.codeSnippet,
                                      language: 'typescript'
                                  });
                              }
                              
                              // 从扩展数据中提取代码片段
                              if (selectedIssue.extensionData) {
                                  Object.entries(selectedIssue.extensionData).forEach(([key, value]) => {
                                      if (key.includes('code_snippet') || key.includes('_code')) {
                                          if (typeof value === 'string') {
                                              codeSnippets.push({
                                                  label: key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
                                                  code: value,
                                                  language: key.includes('cangjie') ? 'cangjie' : key.includes('arkts') ? 'arkts' : 'text'
                                              });
                                          } else if (value && typeof value === 'object' && 'code' in value) {
                                              codeSnippets.push({
                                                  label: (value as any).label || key.replace(/_/g, ' '),
                                                  code: (value as any).code,
                                                  language: (value as any).language || 'text'
                                              });
                                          }
                                      }
                                  });
                              }
                              
                              if (codeSnippets.length === 0) return null;
                              
                              // 单个代码片段：标准展示
                              if (codeSnippets.length === 1) {
                                  return (
                                      <div>
                                          <div className="flex items-center justify-between mb-2">
                                              <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider">Code Context</h3>
                                              <button className="flex items-center gap-1 text-[10px] text-indigo-600 hover:underline font-medium">
                                                  <Copy className="w-3 h-3" /> Copy Code
                                              </button>
                                          </div>
                                          <div className="bg-slate-900 rounded-lg p-4 text-slate-300 font-mono text-xs overflow-x-auto">
                                              <pre>{codeSnippets[0].code}</pre>
                                          </div>
                                      </div>
                                  );
                              }
                              
                              // 两个代码片段：并排展示（适合对比场景）
                              if (codeSnippets.length === 2) {
                                  return (
                                      <div>
                                          <div className="flex items-center justify-between mb-2">
                                              <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider">Code Comparison</h3>
                                          </div>
                                          <div className="grid grid-cols-2 gap-4">
                                              {codeSnippets.map((snippet, idx) => (
                                                  <div key={idx}>
                                                      <div className="flex items-center justify-between mb-2">
                                                          <span className="text-[10px] font-semibold text-slate-500">{snippet.label}</span>
                                                          <button className="flex items-center gap-1 text-[10px] text-indigo-600 hover:underline font-medium">
                                                              <Copy className="w-3 h-3" /> Copy
                                                          </button>
                                                      </div>
                                                      <div className="bg-slate-900 rounded-lg p-4 text-slate-300 font-mono text-xs overflow-x-auto">
                                                          <pre>{snippet.code}</pre>
                                                      </div>
                                                  </div>
                                              ))}
                                          </div>
                                      </div>
                                  );
                              }
                              
                              // 多个代码片段：标签页展示
                              return (
                                  <div>
                                      <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">Code Context</h3>
                                      <div className="border border-slate-200 rounded-lg overflow-hidden">
                                          <div className="flex border-b border-slate-200 bg-slate-50">
                                              {codeSnippets.map((snippet, idx) => (
                                                  <button
                                                      key={idx}
                                                      className={`px-3 py-2 text-xs font-medium border-b-2 transition-colors ${
                                                          idx === 0 
                                                              ? 'border-indigo-500 text-indigo-600 bg-white' 
                                                              : 'border-transparent text-slate-500 hover:text-slate-700'
                                                      }`}
                                                  >
                                                      {snippet.label}
                                                  </button>
                                              ))}
                                          </div>
                                          <div className="bg-slate-900 p-4 text-slate-300 font-mono text-xs overflow-x-auto">
                                              <pre>{codeSnippets[0].code}</pre>
                                          </div>
                                      </div>
                                  </div>
                              );
                          })()}

                          {/* Confirmation Action Section */}
                          <div className="bg-slate-50 rounded-xl border border-slate-200 p-4">
                              <h3 className="text-sm font-bold text-slate-800 mb-4 flex items-center gap-2">
                                  <Check className="w-4 h-4 text-indigo-600" /> Confirm Issue
                              </h3>
                              <div className="space-y-3">
                                  <div>
                                      <label className="block text-xs font-medium text-slate-500 mb-1.5">Confirmation Type</label>
                                      <select 
                                        value={confirmType}
                                        onChange={(e) => setConfirmType(e.target.value as ConfirmationType)}
                                        className="w-full text-sm rounded-lg border-slate-300 focus:border-indigo-500 focus:ring-indigo-500"
                                      >
                                          <option value="" disabled>Please select type...</option>
                                          {Object.values(ConfirmationType).filter(t => t !== 'None').map(t => (
                                              <option key={t} value={t}>{t}</option>
                                          ))}
                                      </select>
                                  </div>
                                  <div>
                                      <label className="block text-xs font-medium text-slate-500 mb-1.5">Remarks (Optional)</label>
                                      <textarea 
                                        value={confirmNote}
                                        onChange={(e) => setConfirmNote(e.target.value)}
                                        maxLength={200}
                                        placeholder="e.g. Root cause, impact scope, fix plan..."
                                        className="w-full h-20 text-sm rounded-lg border-slate-300 focus:border-indigo-500 focus:ring-indigo-500 resize-none"
                                      ></textarea>
                                      <div className="flex justify-between mt-1">
                                          <span className="text-[10px] text-slate-400">Max 200 chars</span>
                                          {selectedIssue.confirmedBy && (
                                              <span className="text-[10px] text-slate-400">Last update: {selectedIssue.confirmedBy}</span>
                                          )}
                                      </div>
                                  </div>
                                  <div className="flex gap-3 pt-2">
                                      <button 
                                        className="flex-1 py-2 text-xs font-semibold text-slate-600 bg-white border border-slate-300 rounded-lg hover:bg-slate-50"
                                        onClick={() => { setConfirmType(''); setConfirmNote(''); }}
                                      >
                                          Cancel
                                      </button>
                                      <button 
                                        onClick={handleConfirmSubmit}
                                        disabled={!confirmType}
                                        className="flex-1 py-2 text-xs font-semibold text-white bg-slate-900 rounded-lg hover:bg-slate-800 disabled:opacity-50 disabled:cursor-not-allowed"
                                      >
                                          Submit
                                      </button>
                                  </div>
                              </div>
                          </div>

                          {/* History Timeline */}
                          {selectedIssue.history.length > 0 && (
                              <div>
                                  <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider mb-4">Audit History</h3>
                                  <div className="border-l-2 border-slate-100 ml-3 space-y-0">
                                      {selectedIssue.history.map((item, idx) => (
                                          <TimelineItem key={item.id} item={item} isLast={idx === selectedIssue.history.length - 1} />
                                      ))}
                                  </div>
                              </div>
                          )}

                          {/* Inheritance Block */}
                          {selectedIssue.inheritedFromRecordId && (
                              <div className="bg-amber-50/50 rounded-xl border border-amber-100 p-4 flex items-start gap-3">
                                  <div className="p-2 bg-amber-100 rounded-lg text-amber-600">
                                      <History className="w-4 h-4" />
                                  </div>
                                  <div>
                                      <p className="text-xs text-amber-800 font-bold">Version Inheritance</p>
                                      <p className="text-xs text-amber-700 mt-1">
                                          Inherited from record <span className="font-mono font-medium">{selectedIssue.inheritedFromRecordId}</span>
                                      </p>
                                      <button className="mt-2 text-[10px] font-bold text-amber-600 bg-white border border-amber-200 px-2 py-1 rounded shadow-sm hover:bg-amber-50">
                                          View History Version
                                      </button>
                                  </div>
                              </div>
                          )}
                      </div>
                  </div>
              </>
          ) : (
             <div className="flex flex-col items-center justify-center h-full text-slate-400">
                 <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mb-4">
                    <ChevronRight className="w-8 h-8 text-slate-300" />
                 </div>
                 <p className="text-sm">Select an issue to view details</p>
             </div> 
          )}
      </div>
    </div>
  );
};
